import express from "express";
import ViteExpress from "vite-express";
import { Client } from '@elastic/elasticsearch';
import { transformLogData, subtractHours } from './utils/logTransformer.js';
import { PrismaClient } from '@prisma/client';

const app = express();
app.use(express.json());
// 创建 Elasticsearch 客户端
const client = new Client({
  node: 'https://10.32.5.237:9200',
  auth: {
    username: 'xaelkuser',
    password: 'xA123456'
  },
  tls: {
    rejectUnauthorized: false
  }
});

/** @type {import('@prisma/client').PrismaClient} */
const prisma = new PrismaClient();

// API 路由
app.get('/api/process/:id', async (req, res) => {
  try {
    const processId = req.params.id;
    const result = await client.search({
      index: 'autotest*',
      size: 4000,
      _source: {
        includes: ['TesterRunner', 'Message', 'AgentName', '@t']
      },
      body: {
        query: {
          bool: {
            filter: [
              {
                term: {
                  'ProcessID.keyword': processId
                }
              },
              {
                bool: {
                  should: [
                    {
                      match_phrase: {
                        Message: 'Start SubTestProcess'
                      }
                    },
                    {
                      match_phrase: {
                        Message: 'End SubTestProcess'
                      }
                    }
                  ]
                }
              }
            ]
          }
        },
        sort: [
          {
            '@t': {
              order: 'asc'
            }
          }
        ]
      }
    });
    const transformedData = transformLogData(result.hits.hits.map(hit => hit._source));
    res.json(transformedData);
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: '数据获取失败' });
  }
});

app.post('/api/process/:id', async (req, res) => {
  const processId = req.params.id;
  const { agentName, startTime, endTime } = req.body;

  const result = await client.search({
    index: 'autotest*',
    size: 100,
    _source: {
      includes: ['StartCaseTime', 'Success', 'EndCaseTime', 'TestCase', 'host.name']
    },
    body: {
      query: {
        bool: {
          filter: [
            {
              bool: {
                must: [
                  {
                    wildcard: {
                      'host.name.keyword': {
                        value: `*${agentName.toLowerCase()}*`,
                        case_insensitive: true
                      }
                    }
                  },
                  {
                    exists: {
                      field: "TestCase"
                    }
                  },
                  {
                    match: {
                      'ProcessID.keyword': processId,
                    }
                  },
                  {
                    range: {
                      "@t": {
                        "gte": new Date(startTime),
                        "lte": new Date(endTime)
                      }
                    }
                  }
                ]
              }
            },

          ]
        }
      },
      sort: [
        {
          '@t': {
            order: 'asc'
          }
        }
      ]
    }
  });

  res.json(result.hits.hits.map(hit => hit._source));
});

// SQL Server API endpoint
app.post('/api/sqlserver/AutoTestActivity', async (req, res) => {
  const { agentName, startTime, endTime } = req.body;

  let convertedStartTime = new Date(startTime);
  let convertedEndTime = new Date(endTime);
  
  convertedStartTime = subtractHours(convertedStartTime, -8);
  // 3.6 秒容错
  convertedEndTime = subtractHours(convertedEndTime, -8.001);

  try {
    /** @type {import('@prisma/client').AutoTestActivity[]} */
    let result = await prisma.autoTestActivity.findMany({
      take: 10, // 限制返回100条数据
      where: {
        StartTime: {
          gte: convertedStartTime, // 查询开始时间
          lte: convertedEndTime, // 查询结束时间
        },
        HostName: agentName
      },
      orderBy: {
        StartTime: 'asc'
      }
    });
    result = result.map(item => {
      return {
        Type: item.Type,
        Tag: item.Tag,
        HostName : item.HostName,
        StartTime: subtractHours(item.StartTime, 8),
        EndTime: subtractHours(item.EndTime, 8),
        Duration: item.Duration,
      };
    });
    res.json(result);
  } catch (error) {
    console.error('Database Error:', error);
    res.status(500).json({ error: '数据库查询失败' });
  }
});

app.post('/api/sqlserver/LargeAutoTestActivity', async (req, res) => {
  const { startTime, endTime } = req.body;
  let convertedStartTime = new Date(startTime);
  let convertedEndTime = new Date(endTime);
  try {
    let result = await prisma.autoTestActivity.findMany({
      take: 10, // 限制返回100条数据
      where: {
        StartTime: {
          gte: convertedStartTime, // 查询开始时间
          lte: convertedEndTime, // 查询结束时间
        },
        Type: {
          notIn: ['Group']
        }
      },
      orderBy: {
        Duration: 'desc'
      }
    });
    result = result.map(item => {
      return {
        Type: item.Type,
        Tag: item.Tag,
        HostName : item.HostName,
        StartTime: item.StartTime,
        EndTime: item.EndTime,
        Duration: item.Duration,
      };
    });
    res.json(result);
  } catch (error) {
    console.error('Database Error:', error);
    res.status(500).json({ error: '数据库查询失败' });
  }
});

ViteExpress.listen(app, 3000, () =>
  console.log("Server is listening on port 3000..."),
);
